package util

import (
	"crypto/tls"
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
	"wxgo/log"
)

// Get 请求
func Get(link string, header map[string]string, params map[string]string) ([]byte, error) {

	client := &http.Client{Timeout: 5 * time.Second}

	//忽略https的证书
	client.Transport = &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	p := url.Values{}
	u, _ := url.Parse(link)

	// 设置url参数
	for k, v := range params {
		p.Set(k, v)
	}

	u.RawQuery = p.Encode()

	req, err := http.NewRequest("GET", u.String(), nil)

	log.Debug(" GET url is ", u.String())

	// 设置header
	for k, v := range header {
		req.Header.Add(k, v)
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		log.Debug(" GET url is exception, http code is ", resp.StatusCode)
		return nil, errors.New("http is exception")
	}

	return ioutil.ReadAll(resp.Body)
}

// PostJSON 提交json数据
func PostJSON(link string, body string) ([]byte, error) {

	log.Debug("POST url is ", link)

	resp, err := http.Post(link, "application/json; charset=utf-8", strings.NewReader(body))
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}
